package com.geek.gkpush.util.http;

import com.geek.gkpush.util.json.JacksonUtils;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

/**
 * <h1>HttpRequest入参参数相关处理工具类。</h1><br/>
 *
 * <h1><br/><a href="https://u.geekbang.org/subject/arch3/100614201">Java 业务架构实战营：https://u.geekbang.org/subject/arch3/100614201</a></h1><br/><h1><a href="https://gitee.com/ylimhhmily/BizArchPracticeCamp">Java 业务架构实战营代码地址：https://gitee.com/ylimhhmily/BizArchPracticeCamp</a></h1><br/><h1><a href="https://u.geekbang.org/subject/java4th/1001148?source=app_share">高级 Java 工程体系课 2023 版：https://u.geekbang.org/subject/java4th/1001148?source=app_share</a></h1><br/><h1><a href="https://time.geekbang.org/column/intro/100312101?tab=catalog">Dubbo 源码剖析与实战：https://time.geekbang.org/column/intro/100312101?tab=catalog</a></h1>
 *
 * @author hmilyylimh
 *         ^_^
 * @version 0.0.1
 *         ^_^
 * @date 2022-02-19
 *
 */
public class ParamsUtils {

    /**
     * <h2>解析并获取 GET 方式的请求数据。</h2>
     *
     * @param request
     * @return
     */
    public static Map<String, Object> parseGetParams(HttpServletRequest request) {
        Map<String, Object> getParams = new HashMap<>();
        Enumeration<String> getEnumeration = request.getParameterNames();
        while (getEnumeration.hasMoreElements()) {
            String paramName = getEnumeration.nextElement();
            String[] values = request.getParameterValues(paramName);
            if (values != null && values.length == 1) {
                if (StringUtils.isNotBlank(values[0])) {
                    getParams.put(paramName, values[0]);
                }
            }
        }

        return getParams;
    }

    /**
     * <h2>通过 Jackson 工具类来解析并获取 POST 方式的请求数据。</h2>
     *
     * @param postJson
     * @return
     */
    public static Map<String, Object> parsePostParams(String postJson) {
        if (StringUtils.isBlank(postJson)) {
            return null;
        }

        return JacksonUtils.fromJson(postJson, Map.class);
    }
}